import { CURDApiBase } from "@/api/curd-api-base";
import downloadApi from "@/api/download-api";
import { ElMessage, ElMessageBox } from "element-plus";
import { nextTick, setTransitionHooks } from "vue";
export default class TableContext {
  title = "";
  selection = true;
  selected = [];
  columns = [];
  data = [];
  loading = false;
  current = 1;
  total = 0;
  pageSize = 10;
  filter: any = {};
  otherFilter: any = {};
  rules = null;
  editData: any = {};
  editVisible = false;
  other: any = {};
  exportLoading = false;
  editLoading = false;
  importLoading = false;
  importFiles = [];
  api: CURDApiBase = null;
  expand = false;
  defaultExpandAll = false;
  rowClassName = "";
  cellClassName = "";
  maxHeight = null;
  searchLoading = false;
  detailApi: (id: string) => Promise<any> = null;
  listApi: (param: any) => Promise<any> = null;
  delApi: (id: string) => Promise<any> = null;
  saveApi: (data: any) => Promise<any> = null;
  batchDeleteApi: (data: any) => Promise<any> = null;
  exportApi: (param: any) => Promise<any> = null;
  formRef = null;
  constructor(public vue, param) {
    if (param) {
      Object.keys(param).forEach((key) => {
        this[key] = param[key];
      });
    }
  }

  // 编辑按钮
  async showEdit(row?, parent?) {
    row = row || {};
    this.editData = { ...row };
    this.editVisible = true;
    const that = this;
    if (row.id) {
      this.editLoading = true;
      this.detailApi = this.detailApi || ((id) => this.api.detail(id));
      const res = await this.detailApi(row.id);
      if (res.success) {
        row = res.data || {};
        that.editData = { ...row };
      }
      this.editLoading = false;
    }
    nextTick(() => {
      that.formRef?.clearValidate();

      nextTick(() => {
        that.formRef?.clearValidate();
        nextTick(() => {
          that.formRef?.clearValidate();
        });
      });
    });
  }

  processFilter() {
    for (const f in this.filter) {
      if (this.filter[f] === "") {
        delete this.filter[f];
      }
    }
    for (const f in this.otherFilter) {
      if (this.filter[f] === "") {
        delete this.otherFilter[f];
      }
    }
  }

  async loadData() {
    this.loading = true;
    this.listApi = this.listApi || ((param) => this.api.list(param));
    this.processFilter();
    const res = await this.listApi({
      current: this.current,
      size: this.pageSize,
      filter: this.filter,
      otherFilter: this.otherFilter,
    });
    this.data = res.data?.records || [];
    this.total = res.data?.total || 0;
    this.loading = false;
  }

  async del(id) {
    this.delApi = this.delApi || ((id) => this.api.del(id));
    ElMessageBox.confirm("是否确认删除当前数据?", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true,
    })
      .then(async () => {
        const res = await this.delApi(id);
        if (res.success) {
          ElMessage.success("删除成功");
        }
        this.loadData();
      })
      .catch((e) => {
        console.log(e);
      });
    (<any>document.activeElement)?.blur &&
      (<any>document.activeElement)?.blur();
  }

  async batchDelete() {
    this.batchDeleteApi =
      this.batchDeleteApi || ((param) => this.api.batchDel(param));
    const ids = this.selected.map((o) => o.id);
    if (ids.length === 0) {
      ElMessage.warning("请先选择数据！");
      return;
    }
    ElMessageBox.confirm("是否确认删除当前选中数据?", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true,
    })
      .then(async () => {
        const res = await this.batchDeleteApi(ids);
        if (res.success) {
          ElMessage.success("删除成功");
          this.loadData();
        }
      })
      .catch((e) => {
        console.log(e);
      });
  }

  closeEdit() {
    this.formRef?.clearValidate();
    (<any>document.activeElement)?.blur &&
      (<any>document.activeElement)?.blur();
  }

  get editAction() {
    return this.editData.id ? "修改" : "新增";
  }

  // 编辑保存按钮
  async save() {
    await this.formRef.validate(async (validated) => {
      if (validated) {
        this.saveApi = this.saveApi || ((param) => this.api.save(param));
        const res = await this.saveApi(this.editData);
        if (res.success) {
          ElMessage.success(`${this.editAction}成功`);
          this.loadData();
          this.editVisible = false;
        }
      }
    });
  }

  // 导出excel
  async export() {
    this.exportLoading = true;
    ElMessageBox.confirm("是否确认导出所有数据?", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true,
    })
      .then(async () => {
        this.exportApi = this.exportApi || ((param) => this.api.export(param));
        this.processFilter();
        const res = await this.exportApi({
          filter: this.filter,
        });
        if (res.success) {
          downloadApi.name(res.msg);
        }
        this.exportLoading = false;
      })
      .catch(() => {
        this.exportLoading = false;
      });
  }
}
